const crypto = require('crypto');
const querystring = require('querystring');
const axios = require('axios');

// 支付宝沙箱配置
const ALIPAY_CONFIG = {
  // 沙箱环境网关
  gatewayUrl: 'https://openapi.alipaydev.com/gateway.do',

  // 应用ID（沙箱环境默认测试应用）
  appId: process.env.ALIPAY_APP_ID || '9021000122671080',

  // 应用私钥
  privateKey: process.env.ALIPAY_PRIVATE_KEY || `-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAjrz0mKIMwVOsXi6+L0y/pRDSj6iOp4s5/dxFyUP5+/V8ZEEA
085gYWXREm3U+8t50K7TZ4eb2ZjiU/zcN28RBAqAkgLO1y8kZSFk+EO2x45qktzhQ
tt0Km5GFQwrCZnpyH6vzVonkIpMpQkiVMNLipTBDzYvpteFS+/ynKjTOom1PyjBU
Fd/Dp9Cl7c5tR9uEz2QDMpJAC2u1xTbZxvqYELWx8sxfrE2uxZVaYiY5VZ76ESyT
pqJR27aFk76OAR8/gdJd3Av3oTAhjjrqfh0QDNLE5YdgUvyLuRwLqZhgihFSCzpJ
PMhb9czhWIUt3NAwb2tD/Pt5lB0WLY/Q7Pi2QIDAQABAoIBAEQlAcE83EoP4GK2f
iWmxnfPqDbdif2DApSn7MlBor8fW9uhDPwRswHM0huyQ9RSOD3guRzcKROhYawnN
Bti8wSy3t7WaFljMET3xHSiH0j2PPsQaJq6mqMHMn4p6QIUcQA/Oz8Wo3zmCeFgk
vtUoWPv0JuqiuVkT0cJrxILp4xyK4epRLS/7f0r+DGrXZ0BRuo1BaWLsETAxlxwI
3kKXLUOBRfvgHEBlznCitoMOBGRLiRFIhIcQ5w/PnWvSY85BwD6XiyM488jb6fKH
reFU3YrqidkfPjpInwmFbcFtE7RoN2IHA144nVZ8p6DMmHrJdlXn8S5WTt8cYEpg
qkZ9YECgYEAvzzx2uWAtq11CGz9KHiPbVhZFHv8l0/QPUEOkjAABV4/vkvNzntev
YuoxeElWHYwlCU5laWbHwkOvZdq0o9HKPzFjDgNcspJopnVARyq0TLv893h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+/ynKjTOom1PyjBUFd/Dp9Cl7c5tR9uEz2QDMpJAC2u1xTbZxvq
YELWx8sxfrE2uxZVaYiY5VZ76ESyTpqJR27aFk76OAR8/gdJd3Av3oTAhjjrqfh0
QDNLE5YdgUvyLuRwLqZhgihFSCzpJPMhb9czhWIUt3NAwb2tD/Pt5lB0WLY/Q7Pi
2QIDAQAB
-----END PUBLIC KEY-----`,

  // 签名类型
  signType: 'RSA2',

  // 字符集
  charset: 'utf-8',

  // 数据格式
  format: 'JSON',

  // API版本
  version: '1.0',

  // 回调地址配置
  notifyUrl: process.env.PAYMENT_NOTIFY_URL || 'http://localhost:3002/api/payments/alipay/notify',
  returnUrl: process.env.PAYMENT_RETURN_URL || 'http://localhost:3000/payment/result'
};

/**
 * 支付宝服务类
 */
class AlipayService {

  /**
   * 生成签名
   */
  generateSign(params) {
    // 排序参数
    const sortedParams = Object.keys(params)
      .filter(key => params[key] && key !== 'sign')
      .sort()
      .map(key => `${key}=${params[key]}`)
      .join('&');

    // 使用私钥签名
    const sign = crypto
      .createSign('RSA-SHA256')
      .update(sortedParams, 'utf8')
      .sign(ALIPAY_CONFIG.privateKey, 'base64');

    return sign;
  }

  /**
   * 验证签名
   */
  verifySign(params, sign) {
    // 排序参数
    const sortedParams = Object.keys(params)
      .filter(key => params[key] && key !== 'sign' && key !== 'sign_type')
      .sort()
      .map(key => `${key}=${params[key]}`)
      .join('&');

    // 使用支付宝公钥验证签名
    const verify = crypto
      .createVerify('RSA-SHA256')
      .update(sortedParams, 'utf8')
      .verify(ALIPAY_CONFIG.alipayPublicKey, sign, 'base64');

    return verify;
  }

  /**
   * 创建支付订单
   */
  async createPayment({ paymentNo, amount, subject, returnUrl, notifyUrl }) {
    try {
      // 构建请求参数
      const bizContent = {
        out_trade_no: paymentNo,
        total_amount: (amount / 100).toFixed(2), // 转换为元
        subject: subject,
        product_code: 'FAST_INSTANT_TRADE_PAY'
      };

      const params = {
        app_id: ALIPAY_CONFIG.appId,
        method: 'alipay.trade.page.pay',
        charset: ALIPAY_CONFIG.charset,
        sign_type: ALIPAY_CONFIG.signType,
        timestamp: new Date().toISOString().replace('T', ' ').substring(0, 19),
        version: ALIPAY_CONFIG.version,
        notify_url: notifyUrl,
        return_url: returnUrl,
        biz_content: JSON.stringify(bizContent)
      };

      // 生成签名
      params.sign = this.generateSign(params);

      // 构建支付URL
      const paymentUrl = `${ALIPAY_CONFIG.gatewayUrl}?${querystring.stringify(params)}`;

      return {
        paymentUrl,
        qrCode: null, // 页面支付不需要二维码
        rawResponse: params
      };

    } catch (error) {
      console.error('创建支付宝支付订单失败:', error);
      throw new Error('创建支付订单失败');
    }
  }

  /**
   * 查询支付状态
   */
  async queryPayment(paymentNo) {
    try {
      const bizContent = {
        out_trade_no: paymentNo
      };

      const params = {
        app_id: ALIPAY_CONFIG.appId,
        method: 'alipay.trade.query',
        charset: ALIPAY_CONFIG.charset,
        sign_type: ALIPAY_CONFIG.signType,
        timestamp: new Date().toISOString().replace('T', ' ').substring(0, 19),
        version: ALIPAY_CONFIG.version,
        biz_content: JSON.stringify(bizContent)
      };

      // 生成签名
      params.sign = this.generateSign(params);

      // 发送请求
      const response = await axios.post(ALIPAY_CONFIG.gatewayUrl, querystring.stringify(params), {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      });

      const result = response.data;
      const queryResponse = result.alipay_trade_query_response;

      if (queryResponse.code === '10000') {
        // 查询成功
        let status = 'pending';

        if (queryResponse.trade_status === 'TRADE_SUCCESS' || queryResponse.trade_status === 'TRADE_FINISHED') {
          status = 'success';
        } else if (queryResponse.trade_status === 'TRADE_CLOSED') {
          status = 'failed';
        }

        return {
          status,
          transactionId: queryResponse.trade_no,
          tradeStatus: queryResponse.trade_status,
          totalAmount: queryResponse.total_amount,
          rawResponse: queryResponse
        };
      } else {
        // 查询失败
        return {
          status: 'failed',
          failureReason: queryResponse.sub_msg || queryResponse.msg,
          rawResponse: queryResponse
        };
      }

    } catch (error) {
      console.error('查询支付宝支付状态失败:', error);
      throw new Error('查询支付状态失败');
    }
  }

  /**
   * 验证回调通知
   */
  async verifyNotify(notifyData) {
    try {
      const sign = notifyData.sign;
      delete notifyData.sign;
      delete notifyData.sign_type;

      return this.verifySign(notifyData, sign);
    } catch (error) {
      console.error('验证支付宝回调签名失败:', error);
      return false;
    }
  }

  /**
   * 申请退款
   */
  async refund({ paymentNo, refundAmount, refundReason }) {
    try {
      const bizContent = {
        out_trade_no: paymentNo,
        refund_amount: (refundAmount / 100).toFixed(2), // 转换为元
        refund_reason: refundReason,
        out_request_no: `REFUND_${paymentNo}_${Date.now()}`
      };

      const params = {
        app_id: ALIPAY_CONFIG.appId,
        method: 'alipay.trade.refund',
        charset: ALIPAY_CONFIG.charset,
        sign_type: ALIPAY_CONFIG.signType,
        timestamp: new Date().toISOString().replace('T', ' ').substring(0, 19),
        version: ALIPAY_CONFIG.version,
        biz_content: JSON.stringify(bizContent)
      };

      // 生成签名
      params.sign = this.generateSign(params);

      // 发送请求
      const response = await axios.post(ALIPAY_CONFIG.gatewayUrl, querystring.stringify(params), {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      });

      const result = response.data;
      const refundResponse = result.alipay_trade_refund_response;

      if (refundResponse.code === '10000') {
        return {
          success: true,
          refundAmount: Math.round(parseFloat(refundResponse.refund_fee) * 100), // 转换为分
          rawResponse: refundResponse
        };
      } else {
        return {
          success: false,
          failureReason: refundResponse.sub_msg || refundResponse.msg,
          rawResponse: refundResponse
        };
      }

    } catch (error) {
      console.error('支付宝退款失败:', error);
      throw new Error('申请退款失败');
    }
  }

  /**
   * 关闭交易
   */
  async closePayment(paymentNo) {
    try {
      const bizContent = {
        out_trade_no: paymentNo
      };

      const params = {
        app_id: ALIPAY_CONFIG.appId,
        method: 'alipay.trade.close',
        charset: ALIPAY_CONFIG.charset,
        sign_type: ALIPAY_CONFIG.signType,
        timestamp: new Date().toISOString().replace('T', ' ').substring(0, 19),
        version: ALIPAY_CONFIG.version,
        biz_content: JSON.stringify(bizContent)
      };

      // 生成签名
      params.sign = this.generateSign(params);

      // 发送请求
      const response = await axios.post(ALIPAY_CONFIG.gatewayUrl, querystring.stringify(params), {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      });

      const result = response.data;
      const closeResponse = result.alipay_trade_close_response;

      return closeResponse.code === '10000';

    } catch (error) {
      console.error('关闭支付宝交易失败:', error);
      return false;
    }
  }
}

module.exports = new AlipayService();
